package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

@Component
@Slf4j
//定时任务类
public class OrderTask {
    @Autowired
    private OrderMapper orderMapper;
    /**
     * 处理超时订单,每分钟执行一次
     */
/*    @Scheduled(cron = "0 * * * * ?")
    public void processTimeOutOrder() {
        log.info("定时器检查超时订单:{}",new Date());
        LocalDateTime localDateTime = LocalDateTime.now().plusMinutes(-15);
        //清理订单状态处于待付款状态且支付超时
        List<Orders> orders = orderMapper.TimeOutOrder(Orders.PENDING_PAYMENT, localDateTime);
        if(orders!=null&orders.size()>0){
            for (Orders order : orders) {
                log.info("定时器处理超时订单:{}",order);
                order.setStatus(Orders.CANCELLED);
                order.setCancelReason("订单超时,自动取消!");
                order.setCancelTime(LocalDateTime.now());
                orderMapper.update(order);
            }
        }
    }*/
    /**
     * 处理一直派送的订单,每天凌晨3:00;04执行一次(与超时订单错开)
     */
    @Scheduled(cron = "4 00 3 * * ?")
    public void processDeliveryOrder(){
        log.info("定时器检查前一天派送的订单:{}",new Date());
        LocalDateTime localDateTime = LocalDateTime.now().plusHours(-1);
        //清理订单状态处于派送中
        List<Orders> orders = orderMapper.TimeOutOrder(Orders.DELIVERY_IN_PROGRESS, localDateTime);
        if(orders!=null&orders.size()>0){
            for (Orders order : orders) {
                log.info("定时器处理前一天派送的订单:{}",order);
                order.setStatus(Orders.COMPLETED);
                orderMapper.update(order);
            }
        }
    }
}
